<template>
  <a-menu
    @click="handleClick"
    :selected-keys="selectedKeys"
    :open-keys="openKeys"
    @openChange="onOpenChange"
    class="h-full"
    mode="inline">
    <template v-for="item in getSidebar">
      <a-menu-item :key="item.routerName" v-if="!item.children">
        <span class="anticon">
          <i :class="item.icon" class=" iconfont m-r-xs"></i>
        </span>
        <span>{{ item.name }}</span>
      </a-menu-item>
      <sub-menu v-else :menu-info="item" />
    </template>
  </a-menu>

</template>

<script>
  import { mapState, mapGetters } from 'vuex'
  import SubMenu from './SubMenu'
  export default {
    name: 'DistSide',
    data () {
      return {
        selectedKeys: [],
        temp: Math.random() * 10000,
        defaultOpenKeys: [],
        rootSubmenuKeys: ['borrowManage', 'custodyManage', 'statistics'],
        openKeys: []
      }
    },
    components: {
      'sub-menu': SubMenu
    },
    created () {
      const route = this.$route
      if (route.query.fromRouter) {
        this.selectedKeys = [route.query.fromRouter]
      } else {
        this.selectedKeys = [route.name]
      }
    },
    mounted () {
      this.Event.$on('_RESTORE_ROUTER_')
    },
    computed: {
      ...mapGetters(['getSidebar']),
      ...mapState(['sidebar'])
    },
    methods: {
      handleClick (e) {
        this.$router.push({ name: e.key })
      },
      onOpenChange (openKeys) {
        const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1)
        if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
          this.openKeys = openKeys
        } else {
          this.openKeys = latestOpenKey ? [latestOpenKey] : []
        }
      }
    },
    watch: {
      '$route' (to, from) {
        if (to.query.fromRouter) {
          this.selectedKeys = [to.query.fromRouter]
        } else {
          this.selectedKeys = [to.name]
        }

        if (to.name === 'borrowApproval' && from.name === 'appHome') {
          this.openKeys = ['borrowManage']
        } else if (to.name === 'reserveManage' && from.name === 'appHome') {
          this.openKeys = ['custodyManage']
        } else if (to.name === 'collectionStatistic' && from.name === 'appHome') {
          this.openKeys = ['statistics']
        }
        // if (!to.query['fromRouter'] || to.query['fromRouter'] !== from.name) {
        //   this.selectedKeys = [to.name]
        // }
      }
    }
  }
</script>

<style scoped lang="less">
  .side{
    height: 100%;
  }

  .ant-menu-item{
    padding-left: 20px!important;
  }
</style>
